﻿using ProjectFootball.MVC.Areas.MatchArea.Models;
using ProjectFootball.MVC.Foundation;
using ProjectFootball.MVC.Models.EntityFramework.Entities;
using ProjectFootball.MVC.Models.RepositoryProviders;
using System;
using System.Linq;
using System.Web.Mvc;

namespace ProjectFootball.MVC.Areas.MatchArea.Controllers
{
    [Authorize]
    public class CreateController : BaseController
    {
        #region Constructor
        public CreateController(IRepositoryProvider provider)
            :base(provider)
        {
        }
        #endregion

        #region /CompetitionArea/Create
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(MatchDataModel matchDataModel)
        {
            if (!ModelState.IsValid)
                return View(matchDataModel);

            Match match = matchDataModel.CreateNew(User);

            if (match.CompetitionGuid != null)
                match.Competition = Provider.CompetitionRepository.Where(c => c.Pk == match.CompetitionGuid).Single();

            if (match.VenueGuid != null)
                match.Venue = Provider.VenueRepository.Where(v => v.Pk == match.VenueGuid).Single();

            if (match.Team1Guid != null)
                match.Team1 = Provider.TeamRepository.Where(v => v.TeamGuid == match.Team1Guid).Single();

            if (match.Team2Guid != null)
                match.Team2 = Provider.TeamRepository.Where(v => v.TeamGuid == match.Team2Guid).Single();

            Provider.MatchRepository.Add(match);
            Provider.SaveChanges();

            return RedirectToAction("Starters", "Edit", new { id = match.Pk });
        }

        [OutputCache(Duration = 0)]
        public JsonResult GetCompetitionsJSON()
        {
            return Json(Provider.CompetitionRepository.GetCodePickerData(), JsonRequestBehavior.AllowGet);
        }

        [OutputCache(Duration = 0)]
        public JsonResult GetVenuesJSON()
        {
            return Json(Provider.VenueRepository.GetCodePickerData(), JsonRequestBehavior.AllowGet);
        }

        [OutputCache(Duration = 0)]
        public JsonResult GetTeamsJSON()
        {
            return Json(Provider.TeamVersionRepository.GetCodePickerData(), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region /CompetitionArea/Create/Events
        public ActionResult Events(Guid id)
        {
            return View();
        }

        [OutputCache(Duration = 0)]
        public JsonResult GetPeopleJSON(string text)
        {
            return Json(Provider.PersonRepository.GetCodePickerData(), JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}
